package com.shijiu.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.shijiu.common.Result;
import com.shijiu.dao.mapper.GoodsMapper;
import com.shijiu.dao.mapper.ShopOrderMapper;
import com.shijiu.dao.mapper.SignMapper;
import com.shijiu.dao.mapper.UserMapper;
import com.shijiu.pojo.*;
import com.shijiu.pojo.ShopOrderVo;
import com.shijiu.service.ShopOrderService;
import com.shijiu.vo.ShopOrderListVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.temporal.Temporal;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;

/**
 * @Author xlj
 * @Date Created in  2023/4/24 16:43
 * @DESCRIPTION:
 * @Version V1.0
 */
@Service
public class ShopOrderServiceImpl extends ServiceImpl<ShopOrderMapper, ShopOrder> implements ShopOrderService {
    @Resource
    private ShopOrderMapper shopOrderMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private GoodsMapper goodsMapper;

    @Resource
    private SignMapper signMapper;
    /**
     * 通过雪花算法生成唯一id
     */
    private static final Snowflake SNOW_FLAKE = IdUtil.getSnowflake(1, 1);

    @Override
    public Result createOrder(Map<String, Object> requestBodyMaps) throws ParseException {
        String username = (String) requestBodyMaps.get("username");
        if (StrUtil.isBlank(username)) {
            return Result.fail(500, "商家用户名为空");
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username);
        User user = userMapper.selectOne(wrapper);
        //获取商家Id
        Integer shopId = user.getId();

        //生成的是不带-的字符串，类似于：b17f24ff026d40949c85a24f4f375d42
        String id = SNOW_FLAKE.nextIdStr();
        String orderId = IdUtil.simpleUUID();
        //获取商品名称
        String orderName = (String) requestBodyMaps.get("name");
        //获取商品下单数量
        Integer orderNum = (Integer) requestBodyMaps.get("num");
        //通过商品id 获取除商品的库存数量
        String commodityId = (String) requestBodyMaps.get("id");
        Goods goods = goodsMapper.selectById(commodityId);

        BigDecimal goodsPrince = goods.getPrince();
        Integer goodsStores = goods.getStores();
        if (orderNum > goodsStores) {
            return Result.fail(500, "库存量不足！！！");
        }
        //更新库存表的库存
        Goods goods1 = new Goods();
        goods1.setId(commodityId);
        goods1.setStores(goodsStores-orderNum);
        goodsMapper.updateById(goods1);
        //获取用户的积分
        LambdaQueryWrapper<Sign> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(Sign::getShopId,shopId);
        Sign sign = signMapper.selectOne(wrapper1);
        Integer integral = sign.getIntegral();
        BigDecimal countMoney = BigDecimal.valueOf((integral * 0.01));
        //获取订单商品的单价
//        BigDecimal shopMoney = (BigDecimal) requestBodyMaps.get("prince");
        //总价格
        BigDecimal prince = goodsPrince.multiply(BigDecimal.valueOf(orderNum));
        // 2.2.1 相减保留两位小数, 直接删除多余的小数位, 如24.417会变成24.41
        BigDecimal subtract1 = prince.subtract(countMoney).setScale(2, BigDecimal.ROUND_DOWN);
        System.out.println(subtract1);

        //获取当前时间
        Date dateTime = new Date();
        // 获取当前时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(dateTime);
        // 将时间增加30分钟
        calendar.add(Calendar.MINUTE, 30);
        // 格式化输出时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String newTime = sdf.format(calendar.getTime());
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date newTimeTwo = dateFormat.parse(newTime);
        ShopOrder shopOrder = new ShopOrder();
        shopOrder.setId(id);
        shopOrder.setOrderNo(orderId);
        shopOrder.setOrderName(orderName);
        shopOrder.setShopId(shopId);
        shopOrder.setCount(orderNum);
        shopOrder.setPrince(subtract1);
        shopOrder.setStatus("0");
        shopOrder.setCreateTime(dateTime);
        shopOrder.setOverTime(newTimeTwo);
        shopOrder.setIsDeleted("0");
        int count = shopOrderMapper.insert(shopOrder);
        return result(count);
    }

    @Override
    public Result selectOrderListByPage(Map<String, Object> requestBodyMaps) throws ParseException {
        Integer pageCount = (Integer) requestBodyMaps.get("page");
        Integer pageSize = (Integer) requestBodyMaps.get("pageSize");
        //商品名称
        String orderName = (String) requestBodyMaps.get("orderName");
        //商家名称
        String shopName = (String) requestBodyMaps.get("shopName");
        //商家名称
        String dianjia = (String) requestBodyMaps.get("dianjia");
        //订单编号
        String orderNo = (String) requestBodyMaps.get("orderNo");
        //状态
        String status = (String) requestBodyMaps.get("status");
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, shopName);
        User user = userMapper.selectOne(wrapper);
        Integer userId = user.getId();
        LambdaQueryWrapper<ShopOrder> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ShopOrder::getIsDeleted, "0");
        ShopOrderListVo shopOrderListVo = new ShopOrderListVo();
        if (StrUtil.isNotBlank(dianjia)) {
            LambdaQueryWrapper<User> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(User::getUsername,dianjia);
            User selectOne = userMapper.selectOne(wrapper1);
            Integer id = selectOne.getId();
            if (id != null) {
                lambdaQueryWrapper.eq(ShopOrder::getShopId, id);
            }
       }
        //如果姓名不为 null 不为空，模糊查询
        if (StrUtil.isNotBlank(orderNo)) {
            lambdaQueryWrapper.eq(ShopOrder::getOrderNo, orderNo);
        }
        //如果商status 不为空
        if (StrUtil.isNotBlank(status)) {
            lambdaQueryWrapper.eq(ShopOrder::getStatus, status);
        }
        ShopOrderVo shopOrderVo = new ShopOrderVo();
        /* 如果是admin 查询所有的 否则根据id 查询每个用户自己的订单。 */
        if ("admin".equals(shopName)) {
            //根据不同的条件查出不同的订单列表
            List<ShopOrder> shopOrders = shopOrderMapper.selectList(lambdaQueryWrapper);
        } else {
            lambdaQueryWrapper.eq(ShopOrder::getShopId, userId);
            //根据不同的条件查出不同的订单列表
            List<ShopOrder> shopOrders = shopOrderMapper.selectList(lambdaQueryWrapper);
            //遍历这个订单列表的每个订单的订单状态（查出所有的订单），
            // 如果有的订单status状态值为 0 ,就遍历 它的下单时间creatTime 值、
            // 然后根据下单时间进行判断下单时间距离现在时间是否超过15分钟，如果超过15分钟就删除该订单;
            for (ShopOrder order : shopOrders) {
                if ("0".equals(order.getStatus())) {
                    Date createTime = order.getCreateTime();
                    Date orderOverTime = order.getOverTime();
                    long betweenMs = DateUtil.betweenMs(orderOverTime, createTime);
                    if (Math.ceil(((float) betweenMs / 60000.0)) > 30) {
                        //取消订单
                        String orderId = order.getId();
                        //将原本的库存退回数据库
                        Integer orderCount = order.getCount();
                        //根据订单名称查询货物的编号
                        String orderNames = order.getOrderName();
                        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
                        queryWrapper.eq(Goods::getName,orderNames);
                        Goods goods = goodsMapper.selectOne(queryWrapper);
                        Goods goods1 = new Goods();
                        goods1.setId(goods.getId());
                        goods1.setStores(goods.getStores()+orderCount);
                        deletedById(orderId);
                    }
                }
            }
        }
        // 查询第pageCount页，每页pageSize条记录
        Page<ShopOrder> page = new Page<>(pageCount, pageSize);
        IPage<ShopOrder> shopOrderPage = shopOrderMapper.selectPage(page, lambdaQueryWrapper);
        // 当前页的记录列表
        List<ShopOrder> shopOrderList = shopOrderPage.getRecords();
        // 总记录数
        List<ShopOrderVo> shopOrderListByName = shopOrderList.stream()
                .map(shopOrder -> {
                    ShopOrderVo shopOrderVos = new ShopOrderVo();
                    // 假设ShopOrder和ShopOrderVo具有相同的字段名，可以使用BeanUtils.copyProperties方法来复制属性
                    BeanUtils.copyProperties(shopOrder, shopOrderVos);
                    Integer shopId = shopOrderVos.getShopId();
                    User byId = userMapper.selectById(shopId);
                    shopOrderVos.setShopName(byId.getUsername());
                    return shopOrderVos;
                })
                .collect(Collectors.toList());
        System.out.println(shopOrderListByName);
        long total = shopOrderPage.getTotal();
        shopOrderListVo.setShopName(shopName);
        shopOrderListVo.setShopOrderVoList(shopOrderListByName);
        shopOrderListVo.setTotal(total);
        return Result.success(shopOrderListVo);
    }
    @Override
    public Result deletedById(String shopOrderId) {
        ShopOrder shopOrder = new ShopOrder();
        shopOrder.setId(shopOrderId);
        shopOrder.setIsDeleted("1");
        int count = shopOrderMapper.updateById(shopOrder);
        return result(count);
    }

    @Override
    public Result selectALL() {
        List<ShopOrder> shopOrderList = shopOrderMapper.selectListAll();
        System.out.println(shopOrderList);
        List<String[]> result = shopOrderList.stream()
                .map(order -> new String[]{order.getOrderName(), order.getCount().toString(), order.getPrince().toString()})
                .collect(Collectors.toList());
        return Result.success(result);
    }

    public static Result result(Integer count) {
        if (count >= 1) {
            return Result.success(count);
        }
        return Result.fail(500, "操作失败，请稍后再试");
    }
}
